package com.moli.iov.gateway.server;


import com.moli.iov.gateway.common.NamedThreadFactory;
import com.moli.iov.util.PropertiesUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * Server端
 *
 * @author <a href="mailto:liws@xingyuanauto.com">liws</a>
 *
 * @version $Revision$
 *
 * @since 2017年1月6日
 */
public class NettyServer {
	
	private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
	/**
	 * server绑定端口
	 */
	private int port;

	public NettyServer(int port) {
		this.port = port;
		bind();
	}

	private void bind(){
		int bossThread = Integer.parseInt(PropertiesUtils.getProperty("netty.boss.thread"));
		int workerThread = Integer.parseInt(PropertiesUtils.getProperty("netty.worker.thread"));
		EventLoopGroup boss = new NioEventLoopGroup(bossThread,new NamedThreadFactory("Netty-Boss",true));
		EventLoopGroup worker = new NioEventLoopGroup(workerThread,new NamedThreadFactory("Netty-Worker",true));

		try{
			//配置服务器的NIO线程租
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(boss, worker);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
			bootstrap.option(ChannelOption.SO_BACKLOG, 1000000);//连接数
			bootstrap.option(ChannelOption.TCP_NODELAY, true);//不延迟，消息立即发送
			bootstrap.option(ChannelOption.SO_KEEPALIVE, true);//长连接
			bootstrap.childHandler(new NettyServerInitializer());
			bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
			// 绑定端口，同步等待成功
			ChannelFuture f = bootstrap.bind(port).sync();
			if(f.isSuccess()){
				logger.info("[GatewayServer]服务启动成功，端口号：" + this.port);
			}
			// 等待服务端监听端口关闭
			f.channel().closeFuture().sync();
		}catch (Exception e) {
			logger.error("[GatewayServer]服务启动异常,异常信息:",e);
		}finally{
			// 释放线程池资源
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
}
